import { FetchResult } from "serve/interface";

export const Fetch = async <F = any, T = any>(url: string, data?: F, init?: RequestInit): Promise<FetchResult<T>> => {
    const res = await fetch(url, {
        credentials: 'include',
        headers: {
            'Content-Type': data instanceof FormData ? 'multipart/form-data' : 'application/json',
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            ...(init?.headers || {})
        },
        method: data ? 'POST' : 'GET',
        body: (data instanceof FormData) ? data : (data && JSON.stringify(data)),
        ...init
    })
    if (res.redirected) {
        window.location.reload()
    }
    return await res.json()
};